﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using Coslen.TahorCRM.Domain.Model.Entities;

namespace Coslen.TahorCRM.Security
{
    /// <summary>
    /// 
    /// <remarks>
    /// Original Source: http://www.mattwrock.com/post/2009/10/14/Implementing-custom-Membership-Provider-and-Role-Provider-for-Authinticating-ASPNET-MVC-Applications.aspx
    /// </remarks>
    /// </summary>
    public class TahorPrincipal : IPrincipal
    {
        public User User { get; set; }
        protected TahorPrincipal() { }

        //public TahorPrincipal(int userId, string userName, string fullName, string password)
        //{
        //    UserId = userId; 
        //    UserName = userName; 
        //    FullName = fullName; 
        //    Password = password;
        //}        
        
        public TahorPrincipal(User user, bool isAuthenticated)
        {
            User = user;
            UserId = User.UserId;
            UserName = User.Username;
            FullName = User.Username;
            Password = User.PasswordHash;

            this.Identity = new TahorIdentity(User.Username, isAuthenticated);
        }

        public virtual int UserId { get; set; }        
        public virtual string UserName { get; set; }        
        public virtual string FullName { get; set; }        
        public virtual string Password { get; set; }    
     
        public virtual IIdentity Identity { get; set; }
        
        public virtual bool IsInRole(string role)
        {
            // Is there any role with the same name???
            if (User.UserRoles.Any(x => x.Role.Name.ToLower() == role.ToLower()))
            {
                return true;
            }

            // Is there any Right for any Role with the same name???
            if (User.UserRoles.Any(x => x.Role.RoleRights.Any( y=> y.Right.Name.ToLower() == role.ToLower())))
            {
                return true;
            }

            return false;
        }
    }
}
